package com.cuiweiyou.bluemesh.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cuiweiyou.bluemesh.R;
import com.cuiweiyou.bluemesh.base.BaseActivity;
import com.cuiweiyou.bluemesh.bluetooth.BluetoothMaster;
import com.cuiweiyou.bluemesh.util.ProcessUtil;
import com.cuiweiyou.bluemesh.util.SPDataUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BlueInitActivity extends BaseActivity {

    @BindView(R.id.groupTabLayout)
    TabLayout groupTabLayout;

    @BindView(R.id.groupViewPager)
    ViewPager groupViewPager;

    @BindView(R.id.meshNameEditText)
    EditText meshNameEditText;

    private GroupInitAdapter groupInitAdapter;
    private List<String> groupList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_init_blue);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);// 设置默认键盘不弹出
        ButterKnife.bind(this);

        initView();
    }

    @OnClick(R.id.addButton)
    public void onAddButtonClicked() {
        addGroup();
    }

    @OnClick(R.id.confirmButton)
    public void onConfirmButtonClicked() {
        confirmInitFinished();
    }

    private void initView() {
        showSoftKeyboard(meshNameEditText);
        meshNameEditText.setOnEditorActionListener(editorActionListener);

        groupTabLayout.setupWithViewPager(groupViewPager);

        groupInitAdapter = new GroupInitAdapter(getSupportFragmentManager());
        groupViewPager.setAdapter(groupInitAdapter);
    }

    private TextView.OnEditorActionListener editorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            switch (actionId) {
                case EditorInfo.IME_ACTION_DONE:
                    hideSoftKeyboard();
                    addGroup();
                    break;
            }

            return true;
        }
    };

    private void addGroup() {
        final String meshName = meshNameEditText.getText().toString().trim();
        if (TextUtils.isEmpty(meshName) || groupList.contains(meshName)) {
            Toast.makeText(this, "请输入灯组名称", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认");
        builder.setMessage("您的灯组名称是：" + meshName + "。");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                addMesh(meshName);
            }
        });
        builder.create().show();
        meshNameEditText.setText("");
    }

    private void addMesh(String meshName) {
        groupList.add(meshName);
        groupInitAdapter.addGroup(meshName);
        groupViewPager.setCurrentItem(groupViewPager.getChildCount() - 1);
    }

    private void confirmInitFinished() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认");
        builder.setMessage("保存灯组数据");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                serializableBlue();
            }
        });
        builder.create().show();
    }

    private void serializableBlue() {
        showProgressDialog();

        ProcessUtil.processBlueGroup(new ProcessUtil.OnProcessBlueGroupFinishListener() {
            @Override
            public void onProcessBlueGroupFinish(boolean success) {
                dismissProgressDialog();

                if (success) {
                    gotoMainAty();
                }else{
                    tryAgain();
                }
            }
        });
    }

    private void tryAgain(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认");
        builder.setMessage("是否再次保存");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                serializableBlue(); // tryAgain
            }
        });
        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.create().show();
    }

    private void gotoMainAty() {
        BluetoothMaster.getInstance().release();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        SPDataUtil.getInstance().saveFirstTimeRunApp(false);

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);

        finish();
    }
}
